package vrpm

import (
	"bytes"
	"encoding/json"
	"errors"
	"github.com/tidwall/gjson"
	"io/ioutil"
	"math/rand"
	"net/http"
	"time"
	"vrcm/src/vrcm/app/admin/models"
	dto "vrcm/src/vrcm/app/admin/service/dto/vrpm"
	"vrcm/src/vrcm/common/service"
	ext "vrcm/src/vrcm/envconfig"
)

var client = http.Client{}

type VrcService struct {
	service.Service
}

var vrpmServiceUrl = "http://172.16.27.50:18899"

// CreateSourcePackAndGroup 创建资源包和用户组
func (e *VrcService) CreateSourcePackAndGroup(d *dto.CreateSourcePackAndGroupReq) (*dto.CreateSourcePackAndGroupRes, error) {

	res := &dto.CreateSourcePackAndGroupRes{}
	urlPath := ext.ExtConfig.ServiceConfig.VrpmServiceUrl + "/v1/client/createSourcePackAndGroup"
	//urlPath := vrpmServiceUrl + "/v1/client/createSourcePackAndGroup"
	// 参数
	data := make(map[string]interface{})
	data["tenant_id"] = d.TenantId
	data["source_pack_name"] = d.SourcePackName
	data["group_name"] = d.GroupName
	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Trace("CreateSourcePackAndGroup：", string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return res, err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return res, err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return res, err
	}
	e.Log.Trace("createSourcePackAndGroup:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return res, errors.New(result.Get("message").String())
	}

	err = json.Unmarshal([]byte(result.Get("data").String()), &res)
	if err != nil {
		e.Log.Errorf("反序列化失败:%s", err)
		return res, err
	}
	return res, nil
}

func (e *VrcService) CreateChannel(d *dto.CreateChannelReq) (*dto.CreateChannelRes, error) {

	res := &dto.CreateChannelRes{}
	createSourcePackAndGroupRes, err := e.CreateSourcePackAndGroup(&dto.CreateSourcePackAndGroupReq{
		SourcePackName: d.Name,
		GroupName:      "group_name",
		TenantId:       d.TenantId,
	})
	if err != nil {
		e.Log.Errorf("CreateSourcePackAndGroup error:%s", err)
		return res, err
	}
	res.SourcePackId = createSourcePackAndGroupRes.SourcePackId
	res.GroupId = createSourcePackAndGroupRes.GroupId
	urlPath := ext.ExtConfig.ServiceConfig.VrpmServiceUrl + "/v1/publish_mgmt2/insertOld"
	//urlPath := vrpmServiceUrl + "/v1/publish_mgmt2/insert"
	// 参数
	data := make(map[string]interface{})
	data["tenantId"] = d.TenantId
	data["channel_number"] = d.ChannelNumber
	data["name"] = d.Name
	data["packageTypeId"] = createSourcePackAndGroupRes.GroupId
	data["channel_logo"] = d.ChannelLogo
	data["description"] = d.Description
	data["descriptionEn"] = d.DescriptionEn
	data["sourcePackId"] = createSourcePackAndGroupRes.SourcePackId
	data["versionId"] = createSourcePackAndGroupRes.VersionId
	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Trace("CreateChannel:", string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return res, err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return res, err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return res, err
	}
	e.Log.Trace("CreateChannel:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return res, errors.New(result.Get("message").String())
	}

	err = json.Unmarshal([]byte(result.Get("data").String()), &res)
	if err != nil {
		e.Log.Errorf("反序列化失败:%s", err)
		return res, err
	}

	//上线
	err = e.StartOrStopChannel(&dto.StartOrStopChannelReq{
		Id:       res.Id,
		Status:   1,
		TenantId: d.TenantId,
	})
	if err != nil {
		e.Log.Errorf("StartOrStopChannel error:%s", err)
		return res, err
	}
	return res, nil
}

func (e *VrcService) SaveProgram(d *dto.SaveProgramReq) (int, error) {

	rand.Seed(time.Now().UnixNano()) // 设置随机数种子

	// 生成4位随机数
	errorCode := rand.Intn(10000)
	urlPath := ext.ExtConfig.ServiceConfig.VrpmServiceUrl + "/v1/epg/create"
	//urlPath := vrpmServiceUrl + "/v1/epg/create"
	// 参数
	data := make(map[string]interface{})
	data["channel_id"] = d.ChannelId
	//epgs := make([]dto.Epg, 0, 5)
	//for _, epg := range d.Epgs {
	//	e := dto.Epg{}
	//	e.StartTime = epg.StartTime
	//	e.EndTime = epg.EndTime
	//	e.ProgramId = epg.ProgramId
	//	e.ChannelId = epg.ChannelId
	//	e.Describe = epg.Describe
	//	e.ProgramName = epg.ProgramName
	//	e.LookUp = epg.LookUp
	//	e.IsSkip = epg.IsSkip
	//	e.Language = epg.Language
	//	e.EventId = epg.EventId
	//	epgs = append(epgs, e)
	//}
	data["epgs"] = d.Epgs
	data["versionId"] = d.VersionId
	//data["versionId"] = d.Epgs
	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Trace("SaveProgram:", string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return errorCode, err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return errorCode, err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return errorCode, err
	}
	e.Log.Trace("SaveProgram:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return errorCode, errors.New(result.Get("message").String())
	}

	return 0, nil
}

func (e *VrcService) GetProgram(d *dto.GetProgramReq) (map[string][]dto.EpgRes, error) {

	epgs := make(map[string][]dto.EpgRes, 5)
	urlPath := ext.ExtConfig.ServiceConfig.VrpmServiceUrl + "/v1/epg/list"
	//urlPath := vrpmServiceUrl + "/v1/epg/list"
	// 参数
	data := make(map[string]interface{})
	data["channel_id"] = d.ChannelId
	data["start_time"] = d.StartTime
	data["end_time"] = d.EndTime
	data["versionId"] = d.VersionId
	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return epgs, err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return epgs, err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return epgs, err
	}
	e.Log.Trace("GetProgram:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return epgs, errors.New(result.Get("message").String())
	}
	err = json.Unmarshal([]byte(result.Get("data").String()), &epgs)
	if err != nil {
		e.Log.Errorf("反序列化失败:%s", err)
		return epgs, err
	}
	return epgs, nil
}

func (e *VrcService) CreatePlayAddress(d *dto.CreatePlayAddressReq) (*dto.CreatePlayAddressRes, error) {

	res := &dto.CreatePlayAddressRes{}
	urlPath := ext.ExtConfig.ServiceConfig.VrpmServiceUrl + "/v1/play_addr/create"
	//urlPath := vrpmServiceUrl + "/v1/play_addr/create"
	// 参数
	data := make(map[string]interface{})
	data["tenantId"] = d.TenantId
	data["channelId"] = d.ChannelId
	data["name"] = d.Name
	data["auto_play_url"] = d.AutoPlayUrl
	data["bitrate_multiple_enable"] = d.BitrateMultipleEnable
	data["codeRate"] = d.CodeRate
	data["is_force"] = d.IsForce
	data["versionId"] = d.VersionId

	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return res, err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return res, err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return res, err
	}
	e.Log.Trace("CreatePlayAddress:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return res, errors.New(result.Get("message").String())
	}

	err = json.Unmarshal([]byte(result.Get("data").String()), &res)
	if err != nil {
		e.Log.Errorf("反序列化失败:%s", err)
		return res, err
	}
	return res, nil
}

func (e *VrcService) DeletePlayAddress(d *dto.DeletePlayAddressReq) error {

	urlPath := ext.ExtConfig.ServiceConfig.VrpmServiceUrl + "/v1/play_addr/delete"
	//urlPath := vrpmServiceUrl + "/v1/play_addr/delete"
	// 参数
	data := make(map[string]interface{})
	data["tenantId"] = d.TenantId
	data["channelId"] = d.ChannelId
	data["id"] = d.Id
	data["versionId"] = d.VersionId
	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("DeletePlayAddress:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}
	return nil
}

func (e *VrcService) StartOrStopChannel(d *dto.StartOrStopChannelReq) error {

	urlPath := ext.ExtConfig.ServiceConfig.VrpmServiceUrl + "/v1/publish_mgmt2/online"
	//urlPath := vrpmServiceUrl + "/v1/publish_mgmt2/online"
	// 参数
	data := make(map[string]interface{})
	data["id"] = d.Id
	data["status"] = d.Status
	data["tenantId"] = d.TenantId
	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("DeletePlayAddress:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}
	return nil
}

func (e *VrcService) DeleteChannel(d *dto.DeleteChannelReq) error {

	urlPath := ext.ExtConfig.ServiceConfig.VrpmServiceUrl + "/v1/publish_mgmt2/delete"
	// 参数
	data := make(map[string]interface{})
	data["id"] = d.Id
	data["tenantId"] = d.TenantId
	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("DeleteChannel:", string(body))
	result := gjson.Parse(string(body))

	//频道不存在
	if result.Get("code").Int() == 7001 {
		return nil
	}
	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}
	return nil
}

func (e *VrcService) DeleteGroup(d *dto.DeleteGroupReq) error {

	urlPath := ext.ExtConfig.ServiceConfig.VrpmServiceUrl + "/v1/package_type/delete"
	// 参数
	data := make(map[string]interface{})
	data["id"] = d.Id
	data["tenantId"] = d.TenantId
	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("DeleteGroup:", string(body))
	result := gjson.Parse(string(body))

	if result.Get("code").Int() == 8001 {
		return nil
	}
	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}
	return nil
}

func (e *VrcService) DeleteSourcePack(d *dto.DeleteSourcePack) error {

	urlPath := ext.ExtConfig.ServiceConfig.VrpmServiceUrl + "/v1/publish_strategy/sourcePackDelete"
	// 参数
	data := make(map[string]interface{})
	data["id"] = d.Id
	data["tenantId"] = d.TenantId
	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("DeleteSourcePack:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() == 3002 {
		return nil
	}
	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}
	return nil
}
